package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.pojo.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.RoleVO;
import com.itheima.pojo.StatusCode;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    //1.新增角色信息
    @RequestMapping("/add")
    public Result add(@RequestBody RoleVO roleVO) {

        try {
            roleService.add(roleVO);
            return new Result(StatusCode.OK, "插入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.OK, "插入失败");
        }
    }


    //2.删除角色信息
    @RequestMapping("/delete")
    public Result delete(@RequestBody  RoleVO roleVO){

        try {
            roleService.delete(roleVO);
            return new Result(StatusCode.OK, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.OK, "删除失败");
        }
    }


    //3.更新角色信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody RoleVO roleVO) {

        try {
            roleService.edit(roleVO);
            return new Result(StatusCode.OK, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.OK, "更新失败");
        }
    }


    //4.获取角色信息列表
    @RequestMapping("/getList")
    public Map getList(@RequestBody RoleVO roleVO) {

        Page<Role> page;
        try {
            page = roleService.getList(roleVO);
            List<Role> roleList = page.getResult();
            long total = page.getTotal();
            Map<String, Object> map = new HashMap<>();
            map.put("records", roleList);
            map.put("total", total);
            map.put("size", roleVO.getPageSize());
            map.put("current", roleVO.getCurrentPage());
            ArrayList<Object> list = new ArrayList<>();
            map.put("orders", list);
            map.put("optimizeCountSql", true);
            map.put("isSearchCount", true);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("code", "success");
            map2.put("data", map);
            return map2;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
